from control.models import *
from literature.models import *
import pandas as pd
from django.db import IntegrityError, transaction
import json
from tqdm import tqdm
import traceback
from datetime import datetime
from basic_component_related_management.models import *
import glob


def init_phase_data():
    super_admin_entity = User.objects.filter(user_account="superadmin").first()
    matched_files = glob.glob("../final_basic_tables/A077. PCdata基表-5-相态表*.xlsx")
    latest_file = max(matched_files, key=lambda x: x.split("-")[-1]) if matched_files else None
    sheet_name = "二级相态表（入库版）"
    df = pd.read_excel(latest_file, sheet_name=sheet_name, header=0, skiprows=[0,2], dtype=str)
    start_row = 0
    num_columns = 8
    selected_data = df.iloc[start_row:, :num_columns].fillna("")

    # print(selected_data)
    # return
    phase_entity_list = []
    for index, row in tqdm(selected_data.iterrows(), desc="Processing phase data"):
        phase_entity = Phase(
            name_en=row["ePhaseNameEN"],
            name=row["ePhaseName"],
            abbreviation=row["sPhaseSymbol"],
            sei_id=row["nPCdataPhaseID"],
            is_pure_used=True,
            is_binary_used=True,
            is_ternary_used=True,
            is_multi_used=True,
            is_reaction_used=True,
            is_complex_used=True,
            description=row["sPhaseDescription"],
            description_en=row["sPhaseDescriptionEN"],
            comment=row["sPhaseComment"],
            create_person=super_admin_entity,
            modify_person=super_admin_entity,
        )
        phase_entity_list.append(phase_entity)
    try:
        with transaction.atomic():
            Phase.objects.bulk_create(phase_entity_list)
    except Exception as e:
        traceback.print_exc()
    return Phase.objects.count() 


def init_phase_content():

    total_phase = init_phase_data()

    print(f"相态录入完成，共录入: {total_phase}")
